// 引入 uni-ajax 模块
// import ajax from '@/uni_modules/u-ajax/js_sdk'
import axios from "axios";
import uniAdapter from './adapters.js'
// import play from '@/utils/play.js'

import { baseUrl } from '@/utils/global'
// import { transferI18n } from "../../main.js"

const defaultConfig = {
  timeout: 30000,
	baseURL: baseUrl,
  adapter: uniAdapter,
  headers: {
    Accept: "application/json, text/plain, */*",
    "Content-Type": "application/json;charset=UTF-8",
    // "X-Requested-With": "XMLHttpRequest",
		languageid: uni.getStorageSync('kLanguage').value || "6"
  },
};

const kTOKENKEY = 'kAuthorizedToken';
class Http {
	constructor() {
		this.isRefreshing = false
		this.requests = []
		this.initConfig = {}
		this.axiosInstance = axios.create(defaultConfig)
		this.httpInterceptorsRequest();
		this.httpInterceptorsResponse();
	}
	
	setBaseUrl() {
		this.axiosInstance.defaults.baseURL = uni.getStorageSync('kBaseUrl')
	}
	
	retryOriginalRequest(config) {
		return new Promise(resolve => {
			this.requests.push((token) => {
				config.headers['Authorization'] = 'Bearer ' + token;
				resolve(config);
			});
		});
	}
	
	
	 // 请求拦截
	  httpInterceptorsRequest() {
			this.axiosInstance.interceptors.request.use(
	      (config) => {
	        // 优先判断post/get等方法是否传入回掉，否则执行初始化设置等回掉
	        if (typeof config.beforeRequestCallback === "function") {
	          config.beforeRequestCallback(config);
	          return config;
	        }
	        if (this.initConfig.beforeRequestCallback) {
	          this.initConfig.beforeRequestCallback(config);
	          return config;
	        }
					// console.log('config.url---------------', config)
					// console.log('kDevelpoment', uni.getStorageSync('kDevelpoment'))
	        const whiteList = [
						"/oauth-service/oauth/token",
						"/nature-permission/api/nt/dict/get_language_by_tenant",
						"/nature-core/api/nt/account/insert_user"
					];
					if (config.url === "/oauth-service/oauth/token") {
						config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
						config.headers['Authorization'] = 'Basic Ym06Ym0='
					}
	        if (whiteList.some((v) => config.url.indexOf(v) > -1)) return config
					
					// console.log(config)
	        return new Promise((resolve) => {
	          const token = uni.getStorageSync('kAuthorizedToken')
						// console.log('token++++++++', token)
	          if (token && token.accessToken) {
	            const expired = 0
	            if (expired) {
	              if (!this.isRefreshing) {
	                this.isRefreshing = true;
	                this.axiosInstance.get("/uath/refreshToken", {
										params: { refreshToken: token.refreshToken },
									}).then((res) => {
	                    // 替换token
	                    this.setToken(res);
	                    config.headers["Authorization"] =
	                      "Bearer " + res.access_token;
	                    // token 刷新后将数组的方法重新执行
	                    // @ts-ignore
	                    this.requests.forEach((cb) => cb(res.access_token));
	                    this.requests = []; // 重新请求完清空
	                  })
	                  .finally(() => {
	                    this.isRefreshing = false;
	                  });
	              }
	              // @ts-ignore
	              resolve(this.retryOriginalRequest(config));
	            } else {
	              config.headers["Authorization"] = "Bearer " + token.accessToken;
	              return resolve(config);
	            }
	          }
	        });
	      },
	      (error) => {
	        return Promise.reject(error);
	      }
	    );
	  }
		
		// 响应拦截
		httpInterceptorsResponse() {
			this.axiosInstance.interceptors.response.use(
				(response) => {
					const config= response.config;
					if (this.initConfig.beforeResponseCallback) {
						this.initConfig.beforeResponseCallback(response);
						return response.data;
					}
					const res = response.data
					uni.hideLoading()
					if (response.status !== 200) {
						return Promise.reject(res)
					} else if ((response.status !== 200 && res.code !== '0') || res.code === '500') {
						return Promise.reject(res)
					} else {
						return Promise.resolve(res.data || res)
					}
				},
				(error) => {
					uni.hideLoading()
					// debugger
					uni.showModal({
						title: 'Error',
						// title: transferI18n("app.tips"),
						content: error.data ? error.data.msg : '服务器异常',
						showCancel: false,
						success: function (res) {}
					})
					// 对响应错误做些什么
					return Promise.reject(error)
				}
			);
		}
		
		 transformConfigByMethod(params, config) {
			const { method } = config;
			const methods = ["get"];
			const m = method.toLocaleLowerCase();
			const props = methods.includes(m) ? "params" : "data";
			return {
				...config,
				[props]: params,
			};
		}
		
		setToken(token) {
		 const { access_token, expires_in, refresh_token } = token;
		 const cache = {
			 accessToken: access_token,
			 refreshToken: refresh_token,
			 expires: Date.now() + expires_in * 1000
		 };
		 uni.setStorageSync(kTOKENKEY, cache)
	 }
		// 通用请求工具函数
		request(method, url, param, axiosConfig){
			const config = this.transformConfigByMethod(param, {method, url, ...axiosConfig });
			// 单独处理自定义请求/响应回掉
			return new Promise((resolve, reject) => {
				this.axiosInstance
					.request(config)
					.then((res) => {
						if (res && res.code === "0") {
							resolve(res.data);
						} else if (res.code === "500") {
							doMessage(res.msg);
							reject(res.msg);
						} else if (res) {
							resolve(res);
						} else {
							const msg = res.msg || "服务异常";
							doMessage(msg);
							reject(msg);
						}
					})
					.catch((e) => {
						if (e.code || e.status) {
							doMessage(e.message || e.msg || e.error)
						}
						reject(e);
					});
			});
		}
		// 单独抽离的post工具函数
		post(url, params, config) {
			return this.request("post", url, params, config);
		}
	
		// 单独抽离的delete工具函数
		delete(url, params, config){
			return this.request("delete", url, params, config);
		}
	
		// 单独抽离的put工具函数
		put(url, params, config){
			return this.request("put", url, params, config);
		}
	
		// 单独抽离的get工具函数
		get(url, params, config){
			for (const key in params) {
				if (!params[key]) delete params[key];
			}
			return this.request("get", url, params, config);
		}
}

// 导出创建后的实例
const ajax = new Http()
export { ajax } 

function reSetBaseUrl() {
	ajax.setBaseUrl()
}

export { reSetBaseUrl }

function doMessage(message) {
		// play.fail()
		console.log('1')
		uni.showModal({
			content: message || '服务器异常',
			showCancel: false,
			success: function (res) {}
		})
}